<template>
  <div class="app-container">
    <h2 style="text-align: center">编辑课程目录</h2>

    <el-steps
      :active="2"
      process-status="wait"
      align-center
      style="margin-bottom: 40px"
    >
      <el-step title="填写课程基本信息" />
      <el-step title="编辑课程目录" />
      <el-step title="最终发布" />
    </el-steps>

    <el-button type="primary" @click="openChapterDialog()">添加章节</el-button>

    <!-- 章节展示 -->
    <el-card
      class="box-card"
      shadow="never"
      style="height: 60vh; overflow: auto"
    >
      <ol class="chanpterList">
        <li v-for="chapter in chapterVideoList" :key="chapter.id">
          <p>
            {{ chapter.title }}
            <span class="acts">
              <el-button style="" type="text" @click="addSubsection(chapter.id)"
                >添加视频小节</el-button
              >
              <el-button
                style=""
                type="text"
                @click="openEditChatper(chapter.id)"
                >编辑</el-button
              >
              <el-button
                type="text"
                @click="removeChapter(chapter.id)"
                style="color: #f56c6c"
                >删除</el-button
              >
            </span>
          </p>

          <!-- 小节展示-->
          <ol class="chanpterList videoList">
            <li v-for="chapter in chapter.children" :key="chapter.id">
              <p>
                {{ chapter.title }}
                <span class="acts"> 
                  <!--点击量显示， 同时使用tranNumber转换数字长度-->
                  <span style="padding-right: 5px;">播放量：{{ chapter.viewCounts }}</span>
                  <el-button type="text" @click="openEditVideo(chapter)"
                    >视频信息</el-button
                  >
                  <el-button type="text" @click="openCourseware(chapter.id)"
                    >课件信息</el-button
                  >
                  <!-- 小节试卷 -->
                  <!-- <el-button type="text" @click="openTestPaper(chapter.id)"
                    >试卷信息</el-button
                  > -->
                  <!-- 小节题目 -->
                  <el-button type="text" @click="viewChapterQuestion(chapter)"
                    >查看题目</el-button
                  >
                  <!-- 学习记录 -->
                  <el-button type="text" @click="videoStudyRecord(chapter)"
                    >学习记录</el-button
                  >
                  <el-button
                    type="text"
                    @click="removeVideo(chapter.id)"
                    style="color: #f56c6c"
                    >删除</el-button
                  >
                </span>
              </p>
            </li>
          </ol>
        </li>
      </ol>
    </el-card>

    <!-- 下方按钮 -->
    <div style="padding: 10px 0; text-align: center">
      <el-button @click="previous">上一步</el-button>
      <el-button :disabled="saveBtnDisabled" type="primary" @click="next" plain
        >下一步</el-button
      >
      <el-button :disabled="saveBtnDisabled" type="success" @click="back" plain
        >返回课程页</el-button
      >
    </div>

    <!-- 视频预览对话框 -->
    <el-dialog title="预览" width="80%" :visible.sync="dialogPlayVisible">
      <play :videosource="videosource" v-if="dialogPlayVisible"></play>
    </el-dialog>

    <!-- 课件信息对话框 -->
    <el-dialog
      title="小节课件"
      width="50%"
      :visible.sync="dialogCoursewareVisible"
    >
      <el-form :model="courseware" label-width="120px">
        <el-form-item label="课件标题">
          <el-input v-model="courseware.title" />
        </el-form-item>
        <el-form-item label="水印文字">
          <el-input
            v-model="courseware.watermark"
            :disabled="watermarkDisabled"
          />
        </el-form-item>
        <el-form-item label="选择课件">
          <el-upload
            ref="upload"
            :on-success="handleCoursewareUploadSuccess"
            :on-exceed="handleUploadExceed"
            :on-remove="handleCoursewareRemove"
            :file-list="fileList"
            :action="coursewareUrl"
            :limit="1"
            accept=".pdf"
            class="upload-demo"
            :disabled="coursewareUploadDisabled"
          >
            <!-- 当前的课件信息 -->
            <!-- <el-button size="small" type="info" v-if="courseware.title">
              {{ courseware.title }}
            </el-button> -->

            <el-button
              size="small"
              type="primary"
              :disabled="coursewareUploadDisabled"
              >选取课件</el-button
            >
            <!-- 删除课件 -->
            <el-button
              style="margin-left: 10px"
              size="small"
              type="danger"
              @click="removeCourseware"
              v-if="coursewareUploadDisabled"
              >删除课件</el-button
            >
            <!-- 预览课件 -->
            <el-button
              style="margin-left: 10px"
              size="small"
              type="success"
              @click="
                previewCourseware(courseware.coursewareSourceWatermarkUrl)
              "
              v-if="coursewareUploadDisabled"
              >预览课件</el-button
            >
            <!-- 上传到服务器 -->
            <!-- <el-button
              style="margin-left: 10px"
              size="small"
              type="success"
              @click="uploadCourseware"
              :disabled="fileList.length === 0"
              >上传</el-button
            > -->
            <div slot="tip" class="el-upload__tip" style="color: #E6A23C;">
              只能上传PDF文件<br>进度条右方出现绿色√，才能点击确认按钮，请耐心等待
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCoursewareVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addOrUpdateCourseware"
          :disabled="saveCoursewareBtnDisabled"
          :loading="coursewareLoadingDisabled"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 预览pdf对话框 -->
    <el-dialog title="预览" :visible.sync="previewPdfDialog">
      <!-- <canvas id="pdf-canvas"></canvas> -->
      <iframe
        id="pdf-iframe"
        :src="pdfUrl"
        width="100%"
        height="600px"
        frameborder="0"
      ></iframe>
    </el-dialog>

    <!-- 试卷信息对话框 -->
    <el-dialog
      title="小节试卷"
      :visible.sync="testPaperDialogVisible"
      :before-close="handleTestPaperClose"
      width="70%"
    >
      <div style="font-size: 18px; color: #67c23a">
        <span v-if="this.hasTestPaper">
          <el-tag type="info">当前试卷</el-tag>
          <span>标题：{{ this.currentTestPaper.eduTestInfo.title }}</span
          ><el-divider direction="vertical"></el-divider
          ><span>适用工种：{{ this.currentTestPaper.courseName }}</span
          ><el-divider direction="vertical"></el-divider
          ><span>适用职级：{{ this.currentTestPaper.grade }}</span
          ><el-divider direction="vertical"></el-divider
          ><span>总分：{{ this.currentTestPaper.eduTestInfo.totalScore }}</span>
          <!-- <el-divider direction="vertical"></el-divider
          ><span>创建时间：{{ this.currentTestPaper.gmtCreate }}</span> -->
          <span style="float: right">
            <!-- 查看试题 -->
            <el-button
              type="primary"
              size="small"
              icon="el-icon-search"
              @click="viewTestPaper"
              >查看试题</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="removeTestPaper"
              >移除试卷</el-button
            >
          </span>
        </span>
        <span v-else>
          <span>暂无试卷</span>
          <!-- 新增试卷按钮 -->
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="addTestPaperDialogVisible = true"
            >新增试卷</el-button
          >
        </span>
      </div>
      <el-divider></el-divider>
      <div>
        <!-- 搜索表单 -->
        <el-form :inline="true">
          <el-tag type="info">查找试卷</el-tag>
          <el-form-item label="试卷标题" size="small">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入试卷标题"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="适用工种" size="small">
            <div class="block">
              <el-cascader
                v-model="queryParams.courseId"
                :options="typeOptions"
                placeholder="默认全部"
                :props="{
                  value: 'id',
                  label: 'courseName',
                  children: 'childrenList',
                  expandTrigger: 'hover',
                }"
                :show-all-levels="false"
                clearable
              ></el-cascader>
            </div>
          </el-form-item>
          <el-form-item size="small" label="工种等级">
            <el-select
              v-model="queryParams.gradeId"
              clearable
              placeholder="全部"
            >
              <el-option
                v-for="item in gradeList"
                :key="item.id"
                :label="item.grade"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item size="small">
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="getTestPaperList"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 信息列表 -->
        <el-table
          border
          :header-cell-style="{ background: '#FAFAFA' }"
          :data="testPaperList"
          :default-sort="{ prop: 'gmtCreate', order: 'descending' }"
          height="50vh"
        >
          <el-table-column prop="eduTestInfo.title" label="标题">
          </el-table-column>
          <el-table-column prop="courseName" label="适用工种">
          </el-table-column>
          <el-table-column prop="grade" label="适用职级"> </el-table-column>
          <el-table-column prop="eduTestInfo.totalScore" label="总分">
          </el-table-column>
          <el-table-column
            label="创建时间"
            prop="gmtCreate"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="bindTestPaper(scope.row.eduTestId)"
                >选择</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="testPaperDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="testPaperDialogVisible = false"
          >确 定</el-button
        >
      </span> -->
    </el-dialog>
    <!-- 添加和修改章节表单 -->
    <el-dialog :visible.sync="dialogChapterFormVisible" title="添加章节">
      <el-form :model="chapter" label-width="120px">
        <el-form-item label="章节标题">
          <el-input v-model="chapter.title" />
        </el-form-item>
        <el-form-item label="章节排序">
          <el-input-number
            v-model="chapter.sort"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogChapterFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加和修改小节表单 -->
    <el-dialog :visible.sync="dialogVideoFormVisible" title="小节视频">
      <el-form :model="video" :rules="rules" label-width="120px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="video.title" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="video.sort"
            :min="0"
            controls-position="right"
          />
        </el-form-item>

        <!-- 上传视频  -->
        <el-form-item label="视频资源" prop="videoSourceId">
          <el-button
            size="small"
            type="primary"
            @click="previewVideo(video)"
            plain
            v-show="video.videoOriginalName"
            icon="el-icon-video-play"
            >播放原视频</el-button
          >
          <div v-if="video.videoSourceId">--需要修改时请重新选择视频--</div>
          <span v-else>（暂无视频）</span>
          <VideoUpload
            :key="timer"
            @upload-success="handleVodUploadSuccess"
            @pre-upload="beginVodUpload"
          ></VideoUpload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVideoFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="saveOrUpdateVideo"
          :disabled="saveVideoBtnDisabled"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 新增试卷对话框 -->
    <el-dialog
      title="新增试卷"
      :visible.sync="addTestPaperDialogVisible"
      :before-close="handleAddTestPaperClose"
      width="50%"
    >
      <el-form
        :model="addTestPaper"
        :rules="addTestRules"
        ref="addTestForm"
        label-width="120px"
      >
        <el-form-item label="试卷标题" prop="title">
          <el-input v-model="addTestPaper.title" />
        </el-form-item>
        <el-form-item label="限时(分钟)" prop="limitTime">
          <el-input-number
            v-model="addTestPaper.limitTime"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="总分" prop="totalScore">
          <el-input-number
            v-model="addTestPaper.totalScore"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addTestPaperDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addChapterTestPaper">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import chapter from "@/api/edu/chapter";
import video from "@/api/edu/videoChapter";
import chapterTestPaper from "@/api/edu/chapterTestPaper";
import { removeVideo } from "@/api/video";
import play from "../video/play";
import VideoUpload from "@/components/VideoUpload";
import { mapGetters } from "vuex";
import { getGradeList } from "@/api/grade";
import { queryTestPaperList, addTest } from "@/api/testPaper";
import { getCategory } from "@/api/classification";
import {
  addCoursewareOfChapter,
  updateCourseware,
  getCoursewareByChapterId,
  removeCoursewareByChapterId,
  removeCourseware,
} from "@/api/courseware";
import { tranNumber } from "@/utils/util.js"

export default {
  components: {
    play,
    VideoUpload,
  },
  computed: {
    ...mapGetters(["companyId"]),
  },

  data() {
    return {
      //课件预览
      previewPdfDialog: false,
      //pdf预览地址
      pdfUrl: "",
      saveBtnDisabled: false, //下一步按钮无效
      saveVideoBtnDisabled: true, //确认按钮无效
      dialogPlayVisible: false, //视频播放弹窗
      videosource: {}, //视频播放源
      courseId: "", //课程id
      chapterVideoList: [],
      chapter: {
        //封装章节数据
        title: "",
        sort: 0,
      },
      video: {
        //小节信息
        title: "",
        sort: 0,
        videoSourceId: "", //云端视频资源ID（必须）
        cover: "",
        videoOriginalName: "",
      },
      videoUrl: process.env.BASE_API + "/vod/uploadVideo", // 视频上传的地址
      dialogChapterFormVisible: false, //章节弹框
      dialogVideoFormVisible: false, //小节弹框
      fileList: [], //上传文件列表
      text: "", //视频上传状态
      progress: 0, //视频上传进度
      coursewareUploadDisabled: false, //课件上传按钮禁用
      coursewareLoadingDisabled: false, //课件操作按钮禁用
      testPaperDialogVisible: false, //试卷选择弹框
      testPaperList: [], //试卷列表
      currentTestPaper: {}, //当前试卷
      hasTestPaper: false, //是否有试卷
      addTestPaperDialogVisible: false, //新增试卷弹框
      addTestPaper: {
        //新增试卷
        title: "",
        limitTime: 0,
        totalScore: 0,
      },
      addTestRules: {
        //新增试卷校验规则
        title: [{ required: true, message: "请输入试卷标题", trigger: "blur" }],
        limitTime: [
          { required: true, message: "请输入限时", trigger: "blur" },
          { type: "number", message: "限时必须为数字值", trigger: "blur" },
        ],
        totalScore: [
          { required: true, message: "请输入总分", trigger: "blur" },
          { type: "number", message: "总分必须为数字值", trigger: "blur" },
        ],
      },
      gradeList: [], //等级列表
      testPaperTochapterId: "", //试卷章节id
      typeOptions: [], //分类列表
      queryParams: {
        //试卷查询参数
        title: "",
        gradeId: "",
        courseId: "",
      },
      rules: {
        //校验规则
        title: [{ required: true, message: "请输入小节标题", trigger: "blur" }],
        sort: [
          {
            required: true,
            message: "请输入小节排序",
            trigger: "blur",
          },
          { type: "number", message: "排序必须为数字值", trigger: "blur" },
        ],
        videoSourceId: [
          { required: true, message: "请上传视频", trigger: "blur" },
        ],
      },
      dialogCoursewareVisible: false, //课件弹框
      watermarkDisabled: false, //水印禁用
      courseware: {
        title: "", //标题
        coursewareSourceUrl: "", //上传后文件URL
        chapterId: "", //章节id
        videoCourseId: "", //视频课程id
        watermark: "", //水印
        courseId: "", //类别
        gradeId: "", //等级id 无
        coursewareSourceWatermarkUrl: "", //无
        cover: "", //封面 无
        coursewareDescription: "", //简介 无
      },
      // 课件上传的地址
      coursewareUrl:
        process.env.BASE_API + "/coursewareOss/uploadOssCoursewareFile",
      saveCoursewareBtnDisabled: true, //确认按钮无效
      timer: 0, //视频组件刷新key
      isUploadBtn: true, //上传或编辑按钮
      tranNumber: tranNumber, //长数字转化
    };
  },
  created() {
    //获取路由的id值
    if (this.$route.params && this.$route.params.id) {
      this.courseId = this.$route.params.id; //课程id
      this.courseware.courseId = this.$route.params.courseId; //分类id
      this.courseware.videoCourseId = this.$route.params.id;
      this.courseware.gradeId = this.$route.params.gradeId;
      this.courseware.kind = this.$route.params.kind;
      //根据课程id查询章节和小节
      this.getChapterVideo();
    }
  },
  methods: {
    //排序方法
    sortArray(x, y) {
      if (x.sort < y.sort) {
        return -1;
      }
      if (x.sort > y.sort) {
        return 1;
      }
      return 0;
    },
    //
    //==============================上传视频过程操作====================================
    //删除已上传的云端视频
    handleVodRemove() {
      //调用接口的删除视频的方法
      // video.deleteAliyunvod(this.video.videoSourceId).then((response) => {
      //   //提示信息
      //   this.$message({
      //     type: "success",
      //     message: "删除视频成功!",
      //   });
      //   //把文件列表清空
      //   this.fileList = [];
      //   //把video视频id和视频名称值清空
      //   this.video.videoSourceId = "";
      //   this.video.videoOriginalName = "";
      // });
    },
    // //点击×调用这个方法
    // beforeVodRemove(file) {
    //   return this.$confirm(`确定移除 ${file.name}？`);
    // },

    beginVodUpload() {
      this.text = "上传中";
      this.saveVideoBtnDisabled = true;
    },
    //上传视频成功调用的方法
    handleVodUploadSuccess(response) {
      //上传视频id赋值
      this.video.videoSourceId = response.videoId;
      //视频大小
      this.video.size = response.fileSize;
      //上传视频名称赋值
      this.video.videoOriginalName = response.fileName;
      //上传视频成功后确认按钮生效
      if (response.success) {
        this.saveVideoBtnDisabled = false;
      }
    },
    handleUploadExceed() {
      this.$message.warning("想要重新上传，请先删除已上传的文件");
    },
    //==============================视频小节操作====================================
    //删除小节
    removeVideo(id) {
      this.$confirm("此操作将删除小节, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //点击确定，执行then方法
        //调用删除的方法
        removeVideo(id).then((response) => {
          removeCoursewareByChapterId(id).then((response) => {
            //提示信息
            this.$message({
              type: "success",
              message: "删除小节成功!",
            });
            //刷新页面
            this.getChapterVideo();
          });
        });
      }); //点击取消，执行catch方法
    },

    //添加小节预处理
    addSubsection(chapterId) {
      this.timer = new Date().getTime();
      //确定按钮有效
      this.saveVideoBtnDisabled = false;
      //弹框
      this.dialogVideoFormVisible = true;
      //表单数据清空
      this.video = {};
      //设置章节id
      this.video.chapterId = chapterId;
      //设置课程分类id
      this.video.courseId = this.courseId;
      //视频类型
      this.video.type = "课程视频";
    },
    //添加小节
    addVideo() {
      this.video.companyId = this.companyId;
      // 判断标题和排序是否为空
      if (!this.video.title || !this.video.sort) {
        this.$message({
          type: "warning",
          message: "标题不能为空、排序需大于0!",
        });
        return;
      }
      //调用添加的方法
      video.addVideo(this.video).then((response) => {
        //关闭弹框
        this.dialogVideoFormVisible = false;
        //提示
        this.$message({
          type: "success",
          message: "添加小节成功!",
        });
        //刷新页面
        this.getChapterVideo();
      });
    },
    //修改小节预处理
    openEditVideo(chapter) {
      //确认按钮生效
      this.saveVideoBtnDisabled = false;
      //弹框
      this.dialogVideoFormVisible = true;
      //调用接口
      video.getVideo(chapter.id).then((response) => {
        this.video = response.data.VideoCourse;
      });
    },
    //修改小节
    updateVideo() {
      this.video.companyId = this.companyId;
      // 判断标题和排序是否为空
      if (!this.video.title || !this.video.sort) {
        this.$message({
          type: "warning",
          message: "标题和排序不能为空!",
        });
        return;
      }
      video.updateVideo(this.video).then((response) => {
        //关闭弹框
        this.dialogVideoFormVisible = false;
        //提示
        this.$message({
          type: "success",
          message: "修改小节成功!",
        });
        //刷新页面
        this.getChapterVideo();
      });
    },
    //添加或者修改小节
    saveOrUpdateVideo() {
      if (!this.video.id) {
        this.addVideo();
      } else {
        this.updateVideo();
      }
    },
    //预览视频
    previewVideo: function (videoSource) {
      this.videosource = videoSource;
      this.dialogPlayVisible = true;
    },
    //==============================课件操作====================================
    //打开课件预处理
    openCourseware(chapterId) {
      this.coursewareUploadDisabled = false;
      this.saveCoursewareBtnDisabled = true;
      this.fileList = [];
      //弹框
      this.courseware.videoCourseId = this.courseId;
      this.courseware.title = "";
      this.courseware.id = "";
      this.courseware.coursewareSourceUrl = "";
      this.courseware.watermark = "";
      this.courseware.chapterId = chapterId;
      this.dialogCoursewareVisible = true;
      this.watermarkDisabled = false;
      //获取课件信息
      getCoursewareByChapterId(chapterId).then((response) => {
        if (response.data.eduCourseware) {
          this.watermarkDisabled = true;
          this.courseware = response.data.eduCourseware.eduCoursewareInfo;
          this.courseware.id = response.data.eduCourseware.id;
          this.fileList = [
            {
              name: this.courseware.title,
              url: this.courseware.coursewareSourceUrl,
            },
          ];
          if (this.courseware) {
            this.coursewareUploadDisabled = true;
            this.saveCoursewareBtnDisabled = false;
          }
        }
      });
    },

    //上传课件成功调用的方法
    handleCoursewareUploadSuccess(response) {
      //上传课件id赋值
      this.courseware.coursewareSourceUrl = response.data.url;
      //上传课件成功后确认按钮生效
      if (response.success) {
        this.saveCoursewareBtnDisabled = false;
      }
    },

    //移除选取的课件
    handleCoursewareRemove() {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    //删除课件
    removeCourseware() {
      var coursewareList = []; //删除列表
      coursewareList.push(this.courseware.id);
      removeCourseware(coursewareList).then((response) => {
        //提示信息
        this.$message({
          type: "success",
          message: "删除课件成功!",
        });
        //把文件列表清空
        this.fileList = [];
        //把video视频id和视频名称值清空
        this.courseware.coursewareSourceUrl = "";
        this.courseware.title = "";
        this.courseware.watermark = "";
        this.saveCoursewareBtnDisabled = true;
        this.coursewareUploadDisabled = false;
        this.dialogCoursewareVisible = false;
      });
    },
    //添加或修改课件
    addOrUpdateCourseware() {
      // 判断标题和课件是否为空
      if (!this.courseware.title || !this.courseware.coursewareSourceUrl) {
        this.$message({
          type: "warning",
          message: "标题和课件不能为空!",
        });
        return;
      }
      this.coursewareLoadingDisabled = true;
      const loading = this.$loading({
        lock: true,
        text: "正在上传课件，暂不能进行其它操作，可能需要几分钟时间，请稍等...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      if (this.courseware.id) {
        updateCourseware(this.courseware).then((response) => {
          loading.close();
          //关闭弹框
          this.dialogCoursewareVisible = false;
          //提示
          this.$message({
            type: "success",
            message: "修改课件成功!",
          });
          this.coursewareLoadingDisabled = false;
          //刷新页面
          this.getChapterVideo();
        });
      } else {
        this.courseware.kind = "0";
        addCoursewareOfChapter(this.courseware).then((response) => {
          loading.close();
          //关闭弹框
          this.dialogCoursewareVisible = false;
          //提示
          this.$message({
            type: "success",
            message: "添加课件成功!",
          });
          this.coursewareLoadingDisabled = false;
          //刷新页面
          this.getChapterVideo();
        });
      }
    },
    //预览课件
    previewCourseware(coursewareSourceWatermarkUrl) {
      this.previewPdfDialog = true;
      this.pdfUrl =
        "static/pdfjs/web/viewer.html?file=" +
        encodeURIComponent(coursewareSourceWatermarkUrl);
    },
    //==============================试卷操作====================================
    //打开试卷选择弹框
    openTestPaper(chapterId) {
      this.testPaperDialogVisible = true;
      this.queryParams.gradeId = this.$route.params.gradeId;
      this.queryParams.courseId = "";
      this.queryParams.title = "";
      this.testPaperTochapterId = chapterId;
      this.getChapterTestPaper();
      this.getTestPaperList();
    },
    //查询小节对应的试卷信息
    getChapterTestPaper() {
      chapterTestPaper
        .getChapterTestPaper(this.testPaperTochapterId)
        .then((response) => {
          this.currentTestPaper = response.data.resTest;
          if (response.data.total) {
            this.hasTestPaper = true;
          } else {
            this.hasTestPaper = false;
          }
        });
    },
    //获取试卷列表
    getTestPaperList() {
      if (this.queryParams.courseId.length > 0) {
        this.queryParams.courseId =
          this.queryParams.courseId[this.queryParams.courseId.length - 1];
      }
      queryTestPaperList(this.queryParams, 1, 10000, this.companyId).then(
        (response) => {
          this.testPaperList = response.data.resList;
        }
      );
      //获取等级列表
      getGradeList().then((res) => {
        this.gradeList = res.data.resList;
      });
      //获取分类列表
      getCategory(0, this.companyId).then((res) => {
        const data = res.data;
        this.typeOptions = this.deleteChildren(data.resList);
      });
    },
    //删除类别中的空childrenList[]
    deleteChildren(arr) {
      let childs = arr;
      for (let i = childs.length; i--; i > 0) {
        if (childs[i].childrenList) {
          if (childs[i].childrenList.length) {
            this.deleteChildren(childs[i].childrenList);
          } else {
            delete childs[i].childrenList;
          }
        }
      }
      return arr;
    },
    //绑定小节试卷
    bindTestPaper(id) {
      //如果存在试卷，提示
      if (this.currentTestPaper) {
        this.$message({
          type: "warning",
          message: "当前章节已绑定试卷，如需修改，请先移除原本的小节试卷!",
        });
        return;
      }
      //调用添加的方法
      chapterTestPaper
        .bindChapterTestPaper(this.testPaperTochapterId, id)
        .then((response) => {
          //提示
          this.$message({
            type: "success",
            message: "绑定试卷成功!",
          });
          //刷新页面
          this.getChapterTestPaper();
        });
    },
    //删除试卷
    removeTestPaper() {
      this.$confirm("此操作将移除当前小节对应的试卷, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(
        () => {
          //调用删除的方法
          chapterTestPaper
            .removeChapterTestPaper(this.testPaperTochapterId)
            .then((response) => {
              //提示信息
              this.$message({
                type: "success",
                message: "删除试卷成功!",
              });
              //刷新页面
              this.getChapterTestPaper();
            });
        } //点击确定，执行then方法
      ); //点击取消，执行catch方法
    },
    //查看试题
    viewTestPaper() {
      this.$router.push({
        name: "Question",
        query: {
          id: this.currentTestPaper.eduTestId,
          title: this.currentTestPaper.eduTestInfo.title,
          totalScore: this.currentTestPaper.eduTestInfo.totalScore,
        },
      });
    },
    //关闭试卷选择弹框
    handleTestPaperClose() {
      this.testPaperDialogVisible = false;
      this.currentTestPaper = {};
      this.hasTestPaper = false;
    },
    //关闭新增试卷弹框
    handleAddTestPaperClose() {
      this.addTestPaperDialogVisible = false;
      this.addTestPaper = {
        title: "",
        limitTime: 0,
        totalScore: 0,
      };
    },
    //添加试卷
    addChapterTestPaper() {
      this.addTestPaper.courseId = this.$route.params.courseId;
      this.addTestPaper.kind = this.$route.params.kind;
      this.addTestPaper.gradeId = this.$route.params.gradeId;
      // 判断表单
      this.$refs.addTestForm.validate((valid) => {
        if (valid) {
          addTest(this.addTestPaper).then((response) => {
            this.$message({
              type: "success",
              message: "添加试卷成功!",
            });
            this.addTestPaperDialogVisible = false;
            this.getTestPaperList();
          });
        } else {
          return false;
        }
      });
    },
    viewChapterQuestion(chapter) {
      this.$router.push({
        name: "ChapterQuestion",
        query: {
          chapterId: chapter.id,
          chapterTitle: chapter.title,
        },
      });
    },
    //==============================章节操作====================================
    //根据课程id查询章节和小节
    getChapterVideo() {
      chapter.getAllChapterVideo(this.courseId).then((response) => {
        var a = response.data.allChapterVideo;
        a.sort(this.sortArray);
        for (let i = 0; i < a.length; ++i) {
          // console.log(a[i].children);
          a[i].children.sort(this.sortArray);
        }
        this.chapterVideoList = a;
        //console.log(this.chapterVideoList);
      });
    },

    //修改章节
    openEditChatper(chapterId) {
      //弹框
      this.dialogChapterFormVisible = true;
      //调用接口
      chapter.getChapter(chapterId).then((response) => {
        this.chapter = response.data.chapter;
      });
    },

    //删除章节
    removeChapter(chapterId) {
      this.$confirm("此操作将删除章节, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //调用删除的方法
        chapter.deleteChapter(chapterId).then((response) => {
          removeCoursewareByChapterId(chapterId).then((response) => {
            //提示信息
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //刷新页面
            this.getChapterVideo();
          });
        });
      }); //点击取消，执行catch方法
    },

    //弹出添加章节页面
    openChapterDialog() {
      //弹框
      this.dialogChapterFormVisible = true;
      //表单数据清空
      this.chapter.title = "";
      this.chapter.sort = 0;
    },

    //添加章节
    addChapter() {
      //设置课程id到chapter对象里面
      this.chapter.courseId = this.courseId;
      chapter.addChapter(this.chapter).then((response) => {
        //关闭弹框
        this.dialogChapterFormVisible = false;
        //提示
        this.$message({
          type: "success",
          message: "添加章节成功!",
        });
        //刷新页面
        this.getChapterVideo();
      });
    },

    //修改章节
    updateChapter() {
      chapter.updateChapter(this.chapter).then((response) => {
        //关闭弹框
        this.dialogChapterFormVisible = false;
        //提示
        this.$message({
          type: "success",
          message: "修改章节成功!",
        });
        //刷新页面
        this.getChapterVideo();
      });
    },

    //判断是添加还是修改
    saveOrUpdate() {
      if (!this.chapter.id) {
        this.addChapter();
      } else {
        this.updateChapter();
      }
    },

    //跳转到学习记录页面
    videoStudyRecord(chapter) {
      this.$router.push({
        name: "VideoStudyRecord",
        query: {
          id: chapter.id,
          videoName: chapter.title,
          type: "1",
        },
      });
    },
    resetQuery() {
      this.queryParams.title = "";
      this.queryParams.gradeId = "";
      this.queryParams.courseId = "";
      this.getTestPaperList();
    },
    previous() {
      this.$router.push({ path: "/info/" + this.courseId });
    },
    next() {
      this.$router.push({
        path: "/publish/" + this.courseId,
        query: {
          courseId: this.$route.params.courseId,
          gradeId: this.$route.params.gradeId,
        },
      });
    },
    back() {
      this.$router.push({ path: "/course" });
    },
  },
};
</script>
<style scoped>
.box-card {
  padding: 0;
  margin-top: 10px;
}
.box-card_body {
  padding: 50px;
}
.chanpterList {
  position: relative;
  list-style: none;
  margin: 0;
  padding: 0;
}
.chanpterList li {
  position: relative;
}
.chanpterList p {
  float: left;
  font-size: 20px;
  margin: 5px;
  padding: 10px;
  height: 30px;
  line-height: 30px;
  width: 99%;
  border: 1px solid #ddd;
}
.chanpterList .acts {
  float: right;
  font-size: 14px;
  padding-right: 20px;
}

.videoList {
  padding-left: 50px;
  padding-right: 10px;
}
.videoList p {
  float: left;
  font-size: 14px;
  margin: 5px;
  padding: 5px;

  height: 30px;
  line-height: 30px;
  width: 100%;
  border: 1px dotted #ddd;
}
</style>